package util;

import entities.TreeNode;
import java.util.Iterator;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class ServletUtil {
    
    public static long getLong(String input, long defaultValue) {
        long result;
        try {
            result = Long.parseLong(input);
        } catch (NumberFormatException ex) {
            result = defaultValue;
        }
        return result;
    }
    
    public static String getCookie(HttpServletRequest request, String name) {
        
        String result = null;
        Cookie[] cookies = request.getCookies();
        
        for(int i = 0; i < cookies.length; i++) { 
            Cookie cookie = cookies[i];
            if (cookie.getName().equals(name)) {
                result = cookie.getValue();
            }
        }
        
        return result;
    }
    
    public static JSONObject treeNodeToJson(TreeNode node, boolean recursive) {
        
        JSONObject nodeJson = new JSONObject();
        JSONArray childsJson = new JSONArray();
        long parentId = (node.getParent() != null) ? node.getParent().getId() : -1;
        
        nodeJson.put("name",      node.getName());
        nodeJson.put("id",        node.getId());
        nodeJson.put("type",      node.getType());
        nodeJson.put("created",   node.getDateCreated().getTimeInMillis());
        nodeJson.put("modified",  node.getDateModified().getTimeInMillis());
        nodeJson.put("childs",    childsJson);
        nodeJson.put("parentId",  parentId);
        
        if (recursive) {
            Iterator<TreeNode> itr = node.getChilds().iterator();
            while (itr.hasNext()) {
                TreeNode child = itr.next();
                childsJson.add(treeNodeToJson(child, true));
            }
        }
        
        return nodeJson;
    }
    
}